package san.web.demo;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.aspectj.util.FileUtil;
import org.springframework.beans.factory.annotation.Autowired;
import com.utils.Page;
import com.web.struts2.CRUDSupportAction;
import san.entity.demo.UpOrDownFile;
import san.entity.dictionary.Dictionary;
import san.service.demo.UpOrDownService;

@SuppressWarnings( { "serial" })
@ParentPackage("fileUpload")
@Results( { @Result(name = "reload", location = "up-or-down.shtml", type = "redirect"),
	@Result(name="down", type="stream", params={"contentType", "application/octet-stream;charset=GBK", "inputName", "inputStream", "contentDisposition", "attachment;filename=${downloadFileName}", "bufferSize", "1024"})	
})
public class UpOrDownAction extends CRUDSupportAction {
	@Autowired
	private UpOrDownService upOrDownService;
	private Page<UpOrDownFile> page = new Page<UpOrDownFile>(10);//每页10条记录
	private UpOrDownFile upOrDownFile = new UpOrDownFile();
	private File upload;
	private String uploadFileName;
	private String uploadContentType;
	public InputStream inputStream;
	private String downloadFileName;
	
	@Override
	protected void prepareModel() throws Exception {
		if (upOrDownFile != null&&StringUtils.isNotBlank(upOrDownFile.getId())) {
			upOrDownFile = upOrDownService.getFileById(upOrDownFile.getId());
		} else {
			if (StringUtils.isNotBlank(getId())) {
				upOrDownFile = upOrDownService.get(getId());
			} else {
				upOrDownFile = new UpOrDownFile();
			}
		}
	}
	
	@Override
	public String list() throws Exception {
		page = upOrDownService.getAllFile(page);
		return SUCCESS;
	}

	@SuppressWarnings( { "finally", "deprecation" })
	@Override
	public String delete() throws Exception {
		try {
			if(StringUtils.isNotBlank(getId())){
				upOrDownFile = upOrDownService
						.getFileById(getId());
				String fileName = getRequest().getRealPath("") + "/upload/"
						+ upOrDownFile.getUploadFileName();
				FileUtil.deleteContents(new File(fileName));
				upOrDownService.removeFile(upOrDownFile);
				addActionMessage("删除成功!");
			}
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			addActionError("删除失败!");
		} finally {
			return RELOAD;
		}
	}

	@SuppressWarnings( { "finally", "deprecation" })
	@Override
	public String save() throws Exception {
		try {
			if(uploadFileName==null){
				addActionMessage("上传文件格式不对");
				return RELOAD;
			}
			String newFileName = RandomStringUtils.randomAlphabetic(9)
					.toLowerCase()
					+ uploadFileName;
			String newPath = getRequest().getRealPath("") + "/upload/"
					+ newFileName;
			File dir = new File(getRequest().getRealPath("") + "/upload");
			if (!dir.exists()) {
				dir.mkdir();
			}
			copy(upload, newPath);
			upOrDownFile.setUploadOldName(uploadFileName);
			upOrDownFile.setUploadFileName(newFileName);
			upOrDownFile.setUploadFileType(uploadContentType);
			upOrDownFile.setUploadFileSize(upload.length());
			upOrDownFile.setUploadFileAuthor(getLoginUser().getUsername());
			upOrDownService.saveOrUpdateFile(upOrDownFile);
			addActionMessage("保存成功!");
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			addActionError("保存失败!");
		} finally {
			return RELOAD;
		}
	}

	@Override
	public String input() throws Exception {
		return INPUT;
	}

	/*
	 * 文件下载
	 */
	@SuppressWarnings("deprecation")
	public String down() throws Exception {
		if(StringUtils.isNotBlank(getId())){
			upOrDownFile = upOrDownService.getFileById(getId());
			String newPath = getRequest().getRealPath("") + "/upload/"
					+ upOrDownFile.getUploadFileName();
			setInputStream(new java.io.FileInputStream(newPath));
			setDownloadFileName(new String(upOrDownFile.getUploadOldName()
					.getBytes("GBK"), "ISO8859-1"));
			return "down";
		} else {
			return RELOAD;
		}
	}

	/**
	 * 拷贝文件
	 * 
	 * @param upload文件流
	 * @param newPath新文件路径和名称
	 * @throws Exception
	 */
	private void copy(File upload, String filePath) throws Exception {
		FileOutputStream fos = new FileOutputStream(filePath);
		FileInputStream fis = new FileInputStream(upload);
		byte[] buffer = new byte[1024];
		int len = 0;
		while ((len = fis.read(buffer)) > 0) {
			fos.write(buffer, 0, len);
		}
		fos.close();
		fis.close();
	}

	// ==================================================

	public Page getPage() {
		return page;
	}

	public void setPage(Page page) {
		this.page = page;
	}

	public UpOrDownFile getUpOrDownFile() {
		return upOrDownFile;
	}

	public void setUpOrDownFile(UpOrDownFile upOrDownFile) {
		this.upOrDownFile = upOrDownFile;
	}

	public File getUpload() {
		return upload;
	}

	public void setUpload(File upload) {
		this.upload = upload;
	}

	public String getUploadFileName() {
		return uploadFileName;
	}

	public void setUploadFileName(String uploadFileName) {
		this.uploadFileName = uploadFileName;
	}

	public String getUploadContentType() {
		return uploadContentType;
	}

	public void setUploadContentType(String uploadContentType) {
		this.uploadContentType = uploadContentType;
	}

	public InputStream getInputStream() {
		return inputStream;
	}

	public void setInputStream(InputStream inputStream) {
		this.inputStream = inputStream;
	}

	public String getDownloadFileName() {
		return downloadFileName;
	}

	public void setDownloadFileName(String downloadFileName) {
		this.downloadFileName = downloadFileName;
	}

}
